package com.nlp.shop.web.controller;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.ActionKey;
import com.nlp.shop.web.util.HttpRequestProxy;
import com.nlp.shop.web.wx.WXSign;
import com.nlp.shop.web.wx.WeiXin;

public class IndexController extends BaseController{
	private static final Log logger = LogFactory.getLog( IndexController.class );//日志
	
	public void index(){
		this.render("index.html");
	}
	
	public void demo(){
		this.render("demo.html");
	}
	
	@ActionKey("/sign")
	public void sign(){
		JSONObject sign = new JSONObject();
		
		String url = getPara("url");
		
		WeiXin.getAccess_tokenForm();
		String api_token = WeiXin.getJsApi_TicketForm();
		Map<String, String> ret = WXSign.sign(api_token, url );
		
		for (Map.Entry<String, String> entry : ret.entrySet()) {
			sign.put(entry.getKey(), entry.getValue());
        }
		sign.put("appId", WeiXin.getAppId() );
		
		this.renderText( sign.toJSONString() );
	}
	
	@ActionKey("/auth")
	public void auth(){
		String code = getPara("code", null);
		
		String openId = userInfo(code);
		
		String from = getPara("from");
		
		this.setCookie("openId", openId, 86400);
		
		this.redirect(from);
		
	}
	
	/**
	 * 根据微信用户授权code，换取access_token,然后获取微信用户基本信息
	 * @param code：授权
	 * @return openId
	 */
	private String userInfo(String code ){
		String reqUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
				"appid=" + WeiXin.getAppId() +
				"&secret=" + WeiXin.getAppSecret() +
				"&code=" + code +
				"&grant_type=authorization_code";
		
		logger.info(reqUrl);
		String result = HttpRequestProxy.doGet(reqUrl, "UTF-8");
		logger.info(result);
		
		JSONObject json = JSONObject.parseObject(result);
		String access_token = null;
		if( json.containsKey("access_token") ){
			access_token = json.getString("access_token");
		}else{
			return null;
		}
		String openId = json.getString("openid");
		
		//获取用户信息
//		String reqinfo = "https://api.weixin.qq.com/sns/userinfo?" +
//				"access_token=" + access_token +
//				"&openid=" + openId +
//				"&lang=zh_CN";
//		
//		logger.info(reqinfo);
//		
//		String userInfo = HttpRequestProxy.doGet(reqinfo, "UTF-8");
//		JSONObject info = JSONObject.parseObject(userInfo);
		
		return openId;
	}
}
